package com.lagou.edu.session;

import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class SessionStorage {

    private Map<String, Session> sessionMap = new HashMap<>();
    private int timeout = 30; //分钟

    public void storeSession(String username) {
        sessionMap.put(username, new Session(new Date(), username));
    }

    public boolean hasSession(String username) {
        Session session = sessionMap.get(username);
        boolean hasSession = false;
        if (session != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(session.loginDate.getTime());
            calendar.add(Calendar.MINUTE, timeout);
            if (!new Date().after(calendar.getTime())) {
                hasSession = true;
            }
        }
        return hasSession;
    }

    class Session {
        private Date loginDate;
        private String username;

        public Session(Date loginDate, String username) {
            this.loginDate = loginDate;
            this.username = username;
        }
    }
}
